package com.huilai.platform.country_platform.controller;

import com.huilai.platform.country_platform.core.AuditEnum2;
import com.huilai.platform.country_platform.core.Msg;
import com.huilai.platform.country_platform.core.TypeEnum;
import com.huilai.platform.country_platform.dto.FeedbackDTO;
import com.huilai.platform.country_platform.model.*;
import com.huilai.platform.country_platform.service.UserService;
import com.huilai.platform.country_platform.service.VillageService;
import com.huilai.platform.country_platform.util.CookieUtil;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：洪霓
 * 日期：2023/3/2
 * 注释：
 */
@Controller
@RequestMapping("/village")
public class VillageController {

    @Autowired
    private VillageService villageService;

    @Autowired
    private UserService userService;

    @RequestMapping("/feedback/reportUI")
    public String reportUI(Model model){
//        村务公开-民事直说-检举控告
        List<String> politicalList = new ArrayList<>();
        politicalList.add("中国共产党党员");
        politicalList.add("中共预备党员");
        politicalList.add("共青团员");
        politicalList.add("民主党派人士");
        politicalList.add("无党派民主人士");
        politicalList.add("群众");

        List<String> levelList = new ArrayList<>();
        levelList.add("正乡科级");
        levelList.add("副乡科级");
        levelList.add("一般干部");
        levelList.add("军队");
        levelList.add("金融机构");
        levelList.add("一般企业");
        levelList.add("事业");
        levelList.add("农村");
        levelList.add("社区");
        levelList.add("其他");

        List<String> categoryList = new ArrayList<>();
        categoryList.add("违反政治纪律");
        categoryList.add("违反组织纪律");
        categoryList.add("违反廉洁纪律");
        categoryList.add("违反群众纪律");
        categoryList.add("违反工作纪律");
        categoryList.add("违反生活纪律");
        categoryList.add("贪污贿赂类行为");
        categoryList.add("滥用职权类行为");
        categoryList.add("玩忽职守类行为");
        categoryList.add("徇私舞弊类行为");
        categoryList.add("重大责任类行为");
        categoryList.add("其他职务类行为");
        model.addAttribute("politicalList",politicalList);
        model.addAttribute("levelList",levelList);
        model.addAttribute("categoryList",categoryList);
        return "village/village-report";
    }

    @RequestMapping("/feedback/complaintUI")
    public String complaintUI(Model model){
//        村务公开-民事直说-群众诉求
        List<String> politicalList = new ArrayList<>();
        politicalList.add("中国共产党党员");
        politicalList.add("中共预备党员");
        politicalList.add("共青团员");
        politicalList.add("民主党派人士");
        politicalList.add("无党派民主人士");
        politicalList.add("群众");

        List<String>categoryList = new ArrayList<>();
        categoryList.add("土地问题");
        categoryList.add("拆迁问题");
        categoryList.add("社会保障");
        categoryList.add("扶贫救灾救济");
        categoryList.add("惠民政策落实");
        categoryList.add("拖欠各类款项");
        categoryList.add("教育医疗服务");
        categoryList.add("基础设施建设");
        categoryList.add("矛盾纠纷");
        categoryList.add("历史遗留");
        categoryList.add("涉法涉诉类");
        categoryList.add("其他类");

        model.addAttribute("politicalList",politicalList);
        model.addAttribute("categoryList",categoryList);
        return "village/village-complaint";
    }

    @RequestMapping("/feedback/proposalUI")
    public String proposalUI(Model model) {
//        村务公开-民事直说-批评建议
        List<String> politicalList = new ArrayList<>();
        politicalList.add("中国共产党党员");
        politicalList.add("中共预备党员");
        politicalList.add("共青团员");
        politicalList.add("民主党派人士");
        politicalList.add("无党派民主人士");
        politicalList.add("群众");
        model.addAttribute("politicalList",politicalList);

        return "village/village-proposal";
    }

    @PostMapping("/addReport")
    @ResponseBody
    public Msg addReport(FeedbackDTO feedbackDTO, HttpServletRequest request){
//        增加村务公开-民事直说-检举控告
        Cookie cookie = CookieUtil.get(request, "username");
        User user = userService.getUserByUsername(cookie.getValue());
        if (cookie == null) {
//            throw new ServiceException("用户未登录");
            return Msg.unLogin();
        }
        FeedbackBe feedbackBe1 = null;
        Integer beFlag = 0;
        FeedbackBe oldFeedbackBe = villageService.findFeedbackBeByNameAndUnitAndPositionAndLevel(feedbackDTO.getBeName(),feedbackDTO.getBeUnit(), feedbackDTO.getBePosition(), feedbackDTO.getBeLevel());
        if (oldFeedbackBe == null){
            FeedbackBe feedbackBe = new FeedbackBe(
                    feedbackDTO.getBeName(),
                    feedbackDTO.getBeUnit(),
                    feedbackDTO.getBePosition(),
                    feedbackDTO.getBeLevel()
            );
            beFlag = villageService.addFeedbackBe(feedbackBe);
            feedbackBe1 = villageService.findFeedbackBeByNameAndUnitAndPositionAndLevel(feedbackBe.getName(), feedbackBe.getUnit(), feedbackBe.getPosition(), feedbackBe.getLevel());
        }else {
            beFlag = 1;
            feedbackBe1 = villageService.findFeedbackBeByNameAndUnitAndPositionAndLevel(feedbackDTO.getBeName(),feedbackDTO.getBeUnit(), feedbackDTO.getBePosition(), feedbackDTO.getBeLevel());
        }

        if (feedbackDTO.getFeedbackName().isEmpty()&&
                feedbackDTO.getFeedbackPostcard().isEmpty()&&
                feedbackDTO.getFeedbackPosition().isEmpty()&&
                feedbackDTO.getFeedbackAddress().isEmpty()&&
                feedbackDTO.getFeedbackPolitical().isEmpty()
                &&feedbackDTO.getFeedbackTelephone().isEmpty()){
            VillageFeedback villageFeedback = new VillageFeedback(
                    null,
                    feedbackBe1.getId(),
                    feedbackDTO.getContentTitle(),
                    feedbackDTO.getContentCategory(),
                    feedbackDTO.getContentMain(),
                    AuditEnum2.getStatusByString(feedbackDTO.getAuditStatus()),
                    TypeEnum.getStatusByString(feedbackDTO.getType())
            );
            Integer feedbackFlag = villageService.addVillageFeedback(villageFeedback);
            VillageFeedback villageFeedback1 = villageService.findVillageFeedbackByContentTitle(villageFeedback.getContentTitle());
            UserFeedback userFeedback = new UserFeedback(
                    user.getId(),
                    villageFeedback1.getId()
            );
            Integer userFeedbackFlag = villageService.addUserFeedback(userFeedback);
            if (beFlag == 1 && feedbackFlag == 1 && userFeedbackFlag == 1) {
                return Msg.success();
            }
        }else {
            FeedbackPerson feedbackPerson2 = null;
            Integer personFlag = 0;
            FeedbackPerson oldFeedbackPerson = villageService.findFeedbackPersonByNameAndPostcard(feedbackDTO.getFeedbackName(), feedbackDTO.getFeedbackPostcard());
            if (oldFeedbackPerson == null){
                FeedbackPerson feedbackPerson1 = new FeedbackPerson(
                        feedbackDTO.getFeedbackName(),
                        feedbackDTO.getFeedbackPostcard(),
                        feedbackDTO.getFeedbackTelephone(),
                        feedbackDTO.getFeedbackPolitical(),
                        feedbackDTO.getFeedbackAddress(),
                        feedbackDTO.getFeedbackPosition());
                personFlag = villageService.addFeedbackPerson(feedbackPerson1);
                feedbackPerson2 = villageService.findFeedbackPersonByNameAndPostcard(feedbackPerson1.getName(), feedbackPerson1.getPostcard());
            }else {
                personFlag = 1;
                feedbackPerson2 = villageService.findFeedbackPersonByNameAndPostcard(feedbackDTO.getFeedbackName(), feedbackDTO.getFeedbackPostcard());
            }
            VillageFeedback villageFeedback = new VillageFeedback(
                    feedbackPerson2.getId(),
                    feedbackBe1.getId(),
                    feedbackDTO.getContentTitle(),
                    feedbackDTO.getContentCategory(),
                    feedbackDTO.getContentMain(),
                    AuditEnum2.getStatusByString(feedbackDTO.getAuditStatus()),
                    TypeEnum.getStatusByString(feedbackDTO.getType())
            );
            Integer feedbackFlag = villageService.addVillageFeedback(villageFeedback);
            VillageFeedback villageFeedback1 = villageService.findVillageFeedbackByContentTitle(villageFeedback.getContentTitle());
            UserFeedback userFeedback = new UserFeedback(
                    user.getId(),
                    villageFeedback1.getFeedbackId()
            );
            Integer userFeedbackFlag = villageService.addUserFeedback(userFeedback);
            if (beFlag == 1 && feedbackFlag == 1 && personFlag == 1 &&userFeedbackFlag == 1) {
                return Msg.success();
            }
        }
        return Msg.fail();
    }

    @PostMapping("/addComplaint")
    @ResponseBody
    public Msg addComplaint(FeedbackDTO feedbackDTO, HttpServletRequest request){
//        增加村务公开-民事直说-群众诉求
        Cookie cookie = CookieUtil.get(request, "username");
        User user = userService.getUserByUsername(cookie.getValue());
        if (cookie == null) {
//            throw new ServiceException("用户未登录");
            return Msg.unLogin();
        }
        FeedbackPerson feedbackPerson1 = null;
        Integer personFlag = 0;
        FeedbackPerson oldFeedbackPerson = villageService.findFeedbackPersonByNameAndPostcard(feedbackDTO.getFeedbackName(), feedbackDTO.getFeedbackPostcard());
        if (oldFeedbackPerson == null){
            FeedbackPerson feedbackPerson = new FeedbackPerson(
                    feedbackDTO.getFeedbackName(),
                    feedbackDTO.getFeedbackPostcard(),
                    feedbackDTO.getFeedbackTelephone(),
                    feedbackDTO.getFeedbackPolitical(),
                    feedbackDTO.getFeedbackAddress(),
                    feedbackDTO.getFeedbackPosition(),
                    feedbackDTO.getComplaintCategory(),
                    feedbackDTO.getComplaintSituation());
            personFlag = villageService.addFeedbackPerson(feedbackPerson);
            feedbackPerson1 = villageService.findFeedbackPersonByNameAndPostcard(feedbackPerson.getName(), feedbackPerson.getPostcard());
        }else {
            oldFeedbackPerson.setComplaintCategory(feedbackDTO.getComplaintCategory());
            oldFeedbackPerson.setComplaintSituation(feedbackDTO.getComplaintSituation());
            personFlag = villageService.updateFeedbackPerson(oldFeedbackPerson);
            feedbackPerson1 = villageService.findFeedbackPersonByNameAndPostcard(feedbackDTO.getFeedbackName(), feedbackDTO.getFeedbackPostcard());
        }

        VillageFeedback villageFeedback = new VillageFeedback(
                feedbackPerson1.getId(),
                null,
                feedbackDTO.getContentTitle(),
                feedbackDTO.getContentCategory(),
                feedbackDTO.getContentMain(),
                AuditEnum2.getStatusByString(feedbackDTO.getAuditStatus()),
                TypeEnum.getStatusByString(feedbackDTO.getType())
        );
        Integer feedbackFlag = villageService.addVillageFeedback(villageFeedback);
        VillageFeedback villageFeedback1 = villageService.findVillageFeedbackByContentTitle(villageFeedback.getContentTitle());
        UserFeedback userFeedback = new UserFeedback(
                user.getId(),
                villageFeedback1.getFeedbackId()
        );
        Integer userFeedbackFlag = villageService.addUserFeedback(userFeedback);
        if (feedbackFlag == 1 && personFlag == 1 && userFeedbackFlag== 1) {
            return Msg.success();
        }
        return Msg.fail();

    }
    @PostMapping("/addProposal")
    @ResponseBody
    public Msg addProposal(FeedbackDTO feedbackDTO,HttpServletRequest request) {
//        增加村务公开-民事直说-批评建议
        Cookie cookie = CookieUtil.get(request, "username");
        User user = userService.getUserByUsername(cookie.getValue());
        if (cookie == null) {
//            throw new ServiceException("用户未登录");
            return Msg.unLogin();
        }
        if (feedbackDTO.getFeedbackName().isEmpty()&&
                feedbackDTO.getFeedbackPostcard().isEmpty()&&
                feedbackDTO.getFeedbackPosition().isEmpty()&&
                feedbackDTO.getFeedbackAddress().isEmpty()&&
                feedbackDTO.getFeedbackPolitical().isEmpty()
                &&feedbackDTO.getFeedbackTelephone().isEmpty()){
            VillageFeedback villageFeedback = new VillageFeedback(
                    null,
                    null,
                    feedbackDTO.getContentTitle(),
                    feedbackDTO.getContentCategory(),
                    feedbackDTO.getContentMain(),
                    AuditEnum2.getStatusByString(feedbackDTO.getAuditStatus()),
                    TypeEnum.getStatusByString(feedbackDTO.getType())
            );
            Integer feedbackFlag = villageService.addVillageFeedback(villageFeedback);
            VillageFeedback villageFeedback1 = villageService.findVillageFeedbackByContentTitle(villageFeedback.getContentTitle());
            UserFeedback userFeedback = new UserFeedback(
                    user.getId(),
                    villageFeedback1.getId()
            );
            Integer userFeedbackFlag = villageService.addUserFeedback(userFeedback);
            if (feedbackFlag == 1 && userFeedbackFlag == 1) {
                return Msg.success();
            }
        }else {
            FeedbackPerson feedbackPerson2 = null;
            Integer personFlag = 0;
            FeedbackPerson oldFeedbackPerson = villageService.findFeedbackPersonByNameAndPostcard(feedbackDTO.getFeedbackName(), feedbackDTO.getFeedbackPostcard());
            if (oldFeedbackPerson == null){
                FeedbackPerson feedbackPerson1 = new FeedbackPerson(
                        feedbackDTO.getFeedbackName(),
                        feedbackDTO.getFeedbackPostcard(),
                        feedbackDTO.getFeedbackTelephone(),
                        feedbackDTO.getFeedbackPolitical(),
                        feedbackDTO.getFeedbackAddress(),
                        feedbackDTO.getFeedbackPosition());
                personFlag = villageService.addFeedbackPerson(feedbackPerson1);
                feedbackPerson2 = villageService.findFeedbackPersonByNameAndPostcard(feedbackPerson1.getName(), feedbackPerson1.getPostcard());
            }else {
                personFlag = 1;
                feedbackPerson2 = villageService.findFeedbackPersonByNameAndPostcard(feedbackDTO.getFeedbackName(), feedbackDTO.getFeedbackPostcard());
            }

            VillageFeedback villageFeedback = new VillageFeedback(
                    feedbackPerson2.getId(),
                    null,
                    feedbackDTO.getContentTitle(),
                    feedbackDTO.getContentCategory(),
                    feedbackDTO.getContentMain(),
                    AuditEnum2.getStatusByString(feedbackDTO.getAuditStatus()),
                    TypeEnum.getStatusByString(feedbackDTO.getType())
            );
            Integer feedbackFlag = villageService.addVillageFeedback(villageFeedback);
            VillageFeedback villageFeedback1 = villageService.findVillageFeedbackByContentTitle(villageFeedback.getContentTitle());
            UserFeedback userFeedback = new UserFeedback(
                    user.getId(),
                    villageFeedback1.getId()
            );
            Integer userFeedbackFlag = villageService.addUserFeedback(userFeedback);
            if (feedbackFlag == 1 && personFlag == 1 && userFeedbackFlag == 1) {
                return Msg.success();
            }

        }
        return Msg.fail();
    }

    @GetMapping("/getDescribeById")
    @ResponseBody
    public Msg getDescribeById(@RequestParam("id")Integer id){
        // 根据id获得VillageFeedback实体
        UserFeedback userFeedback = villageService.findUserFeedbackByFeedbackId(id);
        return Msg.success().add("userFeedback",userFeedback);
    }


    @RequestMapping("/committeeUI")
    public String committeeUI(Model model, @ModelAttribute("searchName") String searchName) {
//        乡务公开-乡委管理
        List<VillageActivities> topActivities1 = villageService.getTopActivities("办事指南");
        model.addAttribute("topActivities1", topActivities1);
        List<VillageActivities> topActivities2 = villageService.getTopActivities("政策法规");
        model.addAttribute("topActivities2", topActivities2);
        List<VillageCommittee> villageCommitteeList1 = villageService.committeeUI(searchName, "公共服务办公室");
        model.addAttribute("villageCommitteeList1", villageCommitteeList1);
        List<VillageCommittee> villageCommitteeList2 = villageService.committeeUI(searchName, "综合治理办公室");
        model.addAttribute("villageCommitteeList2", villageCommitteeList2);
        List<VillageCommittee> villageCommitteeList3 = villageService.committeeUI(searchName, "综合行政执法办公室");
        model.addAttribute("villageCommitteeList3", villageCommitteeList3);
        List<VillageCommittee> villageCommitteeList4 = villageService.committeeUI(searchName, "经济发展办公室");
        model.addAttribute("villageCommitteeList4", villageCommitteeList4);
        List<VillageCommittee> villageCommitteeList5 = villageService.committeeUI(searchName, "农业农村办公室");
        model.addAttribute("villageCommitteeList5", villageCommitteeList5);
        List<VillageCommittee> villageCommitteeList6 = villageService.committeeUI(searchName, "应急管理办公室");
        model.addAttribute("villageCommitteeList6", villageCommitteeList6);
        model.addAttribute("activeTab", "乡委管理");
        return "village/village-committee";
    }

    @RequestMapping("/committeeDetailsUI")
    public String committeeDetailsUI(Model model, @ModelAttribute("id")Integer id){
        List<VillageActivities> topActivities1 = villageService.getTopActivities("政务公开");
        model.addAttribute("topActivities1", topActivities1);
        List<VillageActivities> topActivities2 = villageService.getTopActivities("乡风文明");
        model.addAttribute("topActivities2", topActivities2);
        VillageCommittee villageCommittee = villageService.findCommitteeById(id);
        model.addAttribute("villageCommittee", villageCommittee);
        return "village/village-committee-details";
    }

    @RequestMapping("/activitiesUI")
    public String activitiesUI(Model model, @ModelAttribute("searchName")String searchName, @ModelAttribute("contentType")String contentType,  @PageableDefault(size = 10) Pageable pageable){
//        乡务公开-政务公开等
        List<VillageActivities> topActivities1 = villageService.getTopActivities("办事指南");
        model.addAttribute("topActivities1", topActivities1);
        List<VillageActivities> topActivities2 = villageService.getTopActivities("政策法规");
        model.addAttribute("topActivities2", topActivities2);
        Page<VillageActivities> page = villageService.activitiesUI(searchName, contentType, pageable);
        model.addAttribute("page", page);
        model.addAttribute("activeTab",contentType);
        return "village/village-activities";
    }

    @RequestMapping("/activitiesDetailsUI")
    public String activitiesDetailsUI(Model model, @ModelAttribute("id")Integer id, @PageableDefault(size = 10)Pageable pageable){
        List<VillageActivities> topActivities1 = villageService.getTopActivities("办事指南");
        model.addAttribute("topActivities1", topActivities1);
        List<VillageActivities> topActivities2 = villageService.getTopActivities("政策法规");
        model.addAttribute("topActivities2", topActivities2);
        VillageActivities villageActivities = villageService.findActivitiesyId(id);
        model.addAttribute("villageActivities",villageActivities);
        model.addAttribute("contentType", villageActivities.getContentType());
        return "village/village-activities-details";
    }


    @RequestMapping("/downloadFile")
    public String downloadFile(HttpServletResponse response, @ModelAttribute("filename")String filename) throws UnsupportedEncodingException {
        String rfile = "D:/ideaProject/country_platform/src/main/resources/static/files";
        File file = new File(rfile + File.separator + filename);
        if (file.exists()){
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try{
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}
